<?php
//require("Constants.php");

class CommonUtils {

    var $datasec  = array();
    var $ctrl_dir = array();
    var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
    var $old_offset   = 0;

    function getTextAnswer($a){
        switch($a){
            case 0:
                return 'A';
            case 1:
                return 'B';
            case 2:
                return 'C';
            case 3:     
                return 'D';
            
        }
    }
    function generateID(){
        $magic = "KHANGHY";
        return md5(uniqid($magic . date('Ymd') .rand()));
    }
    
    function checkOverlap($fDate, $toDate, $fromCheck, $toCheck){
        if (($this->compareDate($fDate, $toCheck) >= 0) || ($this->compareDate($fromCheck, $toDate) >= 0)){
            return false;
        }
        return true;
    }

    
    function formatDate($date, $format) {
        if (trim($date) == "")
            return "";
        $y = substr($date, 0, 4);
        $m = substr($date, 5, 2);
        $d = substr($date, 8, 2);
        $s = (int) substr($date, -2, 2);
        $i = (int) substr($date, -5, 2);
        $h = (int) substr($date, -7, 2);
        return date($format, mktime($h,$i,$s,$m,$d,$y));
    }

    function compareDate($date1, $date2) {
        $y1 = substr($date1, 0, 4);
        $m1 = substr($date1, 5, 2);
        $d1 = substr($date1, 8, 2);
        $y2 = substr($date2, 0, 4);
        $m2 = substr($date2, 5, 2);
        $d2 = substr($date2, 8, 2);
        if ($y1 < $y2) return -1;
        else if($y1 > $y2) return 1;
        else {
            if ($m1 < $m2) return -1;
            else if ($m1 > $m2) return 1;
            else {
                if ($d1 < $d2) return -1;
                else if($d1 > $d2) return 1;
                else return 0;
            }
        }
        return 0;
    }
    function formatDecNumber($value,$point=0){
        $res = number_format($value, $point, '.', ',');
        return $curr . $res;
    }
    function duration($date1, $date2, $split = "/"){
        $date1 = substr($date1, 0, 10);
        $date2 = substr($date2, 0, 10);
       
        
        list($y1, $m1, $d1) = explode($split, $date1);
        list($y2, $m2, $d2) = explode($split, $date2);
        
        $res =  (int)((mktime(23, 59, 59, $m1, $d1, $y1) - mktime(0, 0, 0, $m2, $d2, $y2)) / (24 * 3600));

        return $res;
    }
    function timePost($d){
        $ts = time() - strtotime(str_replace("-", "/" ,$d));
        
        if($ts>31536000) $val = round($ts/31536000,0).' năm';
        else if($ts>2419200) $val = round($ts/2419200,0).' tháng';
        else if($ts>604800) $val = round($ts/604800,0).' tuần';
        else if($ts>86400) $val = round($ts/86400,0).' ngày';
        else if($ts>3600) $val = round($ts/3600,0).' giờ';
        else if($ts>60) $val = round($ts/60,0).' phút';
        else if($ts > -1) $val = $ts.' giây';
        else $val="vài giây";
        return $val.' trước';
    }
    
    
    /**
    * @desc Funtion addDate
    *       $date : Y-m-d
    */
    function addDate($date, $more = 0){
        if ($date == ""){
            return "";
        }
        list($y, $m, $d) = explode('-', $date);
        $res = date("Y-m-d", mktime(0, 0, 0, $m, $d, $y) + $more * 3600 * 24);
        return $res;
    }
    
    function randomNumber($number)
    {
        if($number)
        {
            $total = "";
            for($i=1;$i<=$number;$i++)
            {
                $nr=rand(0,9);
                $total=$total.$nr;
            }
        }
        return $total;
    }

    function formatCurrency($value, $curr = 'VND'){
        $res = number_format($value, 0, '.', ',');
        return $res . " " . $curr;
    }

    
    function delfile($filename, $path) {
        $delres = @unlink($path . "/" .  $filename);
        if ($delres) {
            return SUCC;
        }
        else {
            return ERROR;
        }
    }

    function uploadfile($source, $des, $path, $width, $height, $max_size){
        $default_extension = ".gif";
        $mode = 1;
        $my_uploader = new Uploader("en");
        $my_uploader->max_filesize($max_size); // 1000KB = 1000000
        $my_uploader->max_image_size($width, $height);
        $my_uploader->setDesFileName($des);
        if ($my_uploader->upload($source, "", $default_extension)) {
            $my_uploader->save_file($path, $mode);
        }
        if ($my_uploader->error) {
            return $my_uploader->error;
        }
        return SUCC;
    }

    function isImageFile($extension){
        if ($extension == ".jpg" || $extension == ".png" || $extension == ".gif" || $extension == ".bmp" 
            || $extension == ".JPG" || $extension == ".PNG" || $extension == ".GIF" || $extension == ".BMP" ){
            return true;
        }
        return false;
    }
    function readImagesFile($dir){
        $result = array();
        $handle = opendir($dir);
        $i = 0;
        if ($handle) {
            while(false !== ($file = readdir($handle))){
                $extension = substr($file, -4, 4);
                if ($this->isImageFile($extension)){
                    $result[] = $file;
                }
            }
        }
        return $result;
    }  
    function randNum(){
        mt_srand((double)microtime()*1000000);
        $num = mt_rand(46,122);
        return $num;
    }
    function randChar(){
        do {
            $num = $this->randNum();
        } while ( ( $num > 57 && $num < 65 ) || ( $num > 90 && $num < 97 ) );
        $char = chr($num);
        return $char;
    }
    //Function: genSalt
    //Description: Randomize tring for encryption
    function genSalt(){
        $a = $this->randChar();
        $b = $this->randChar();
        $salt = "$a$b";
        return $salt;
    }


    function isFile($extension){
        if ($extension == ".jpg" || $extension == ".png" || $extension == ".gif" || $extension == ".bmp" || $extension==".txt"){
            return true;
        }
        return false;
    }

    function isFlashFile($extension){
        if($extension == ".swf")
            return true;
        return false;
    }
	function readFlashFile($dir){        
        $result = array();
        $handle = opendir($dir);
        $i = 0;
        if ($handle) {
            while(false !== ($file = readdir($handle))){
                $extension = substr($file, -4, 4);
                if ($this->isFlashFile($extension)){
                    $result[] = $file;
                }
            }
        }
        return $result;
    }
    function readFile($dir){
        $result = array();
        $handle = opendir($dir);
        $i = 0;
        if ($handle) {
            while(false !== ($file = readdir($handle))){
                $extension = substr($file, -4, 4);
                if ($this->isFile($extension)){
                    $result[] = $file;
                }
            }
        }
        return $result;
    }
    //Zip File Function
    function unix2DosTime($unixtime = 0) {
        $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);

        if ($timearray['year'] < 1980) {
            $timearray['year']    = 1980;
            $timearray['mon']     = 1;
            $timearray['mday']    = 1;
            $timearray['hours']   = 0;
            $timearray['minutes'] = 0;
            $timearray['seconds'] = 0;
        } // end if

        return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
                ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
    }
    function addFile($data, $name, $time = 0)
    {
        $name     = str_replace('\\', '/', $name);

        $dtime    = dechex($this->unix2DosTime($time));
        $hexdtime = '\x' . $dtime[6] . $dtime[7]
                  . '\x' . $dtime[4] . $dtime[5]
                  . '\x' . $dtime[2] . $dtime[3]
                  . '\x' . $dtime[0] . $dtime[1];
        eval('$hexdtime = "' . $hexdtime . '";');

        $fr   = "\x50\x4b\x03\x04";
        $fr   .= "\x14\x00";            // ver needed to extract
        $fr   .= "\x00\x00";            // gen purpose bit flag
        $fr   .= "\x08\x00";            // compression method
        $fr   .= $hexdtime;             // last mod time and date

        // "local file header" segment
        $unc_len = strlen($data);
        $crc     = crc32($data);
        $zdata   = gzcompress($data);
        $zdata   = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
        $c_len   = strlen($zdata);
        $fr      .= pack('V', $crc);             // crc32
        $fr      .= pack('V', $c_len);           // compressed filesize
        $fr      .= pack('V', $unc_len);         // uncompressed filesize
        $fr      .= pack('v', strlen($name));    // length of filename
        $fr      .= pack('v', 0);                // extra field length
        $fr      .= $name;

        // "file data" segment
        $fr .= $zdata;

        // "data descriptor" segment (optional but necessary if archive is not
        // served as file)
        $fr .= pack('V', $crc);                 // crc32
        $fr .= pack('V', $c_len);               // compressed filesize
        $fr .= pack('V', $unc_len);             // uncompressed filesize

        // add this entry to array
        $this -> datasec[] = $fr;

        // now add to central directory record
        $cdrec = "\x50\x4b\x01\x02";
        $cdrec .= "\x00\x00";                // version made by
        $cdrec .= "\x14\x00";                // version needed to extract
        $cdrec .= "\x00\x00";                // gen purpose bit flag
        $cdrec .= "\x08\x00";                // compression method
        $cdrec .= $hexdtime;                 // last mod time & date
        $cdrec .= pack('V', $crc);           // crc32
        $cdrec .= pack('V', $c_len);         // compressed filesize
        $cdrec .= pack('V', $unc_len);       // uncompressed filesize
        $cdrec .= pack('v', strlen($name) ); // length of filename
        $cdrec .= pack('v', 0 );             // extra field length
        $cdrec .= pack('v', 0 );             // file comment length
        $cdrec .= pack('v', 0 );             // disk number start
        $cdrec .= pack('v', 0 );             // internal file attributes
        $cdrec .= pack('V', 32 );            // external file attributes - 'archive' bit set

        $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
        $this -> old_offset += strlen($fr);

        $cdrec .= $name;

        $this -> ctrl_dir[] = $cdrec;
    }
    function file()
    {
        $data    = implode('', $this -> datasec);
        $ctrldir = implode('', $this -> ctrl_dir);

        return
            $data .
            $ctrldir .
            $this -> eof_ctrl_dir .
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries "on this disk"
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries overall
            pack('V', strlen($ctrldir)) .           // size of central dir
            pack('V', strlen($data)) .              // offset to start of central dir
            "\x00\x00";                             // .zip file comment length
    }
    function addFiles($files /*Only Pass Array*/)
    {
        foreach($files as $file)
        {
        if (is_file($file)) //directory check
        {
            $data = implode("",file($file));
                    $this->addFile($data,$file);
                }
        }
    }
    /*
        function doZipFile($filesrc, $filedes): nen file
            $filesrc : la danh sach cac file can nen: phai la array
            $filedes : ten file dich
        VD:
            $utils = new CommonUtils();
            u$tils->doZipFile(array("a.txt","b.png"),"data/des.zip");

    */
    function doZipFile($filesrc, $filedes)
    {
        foreach($filesrc as $file)
        {
        if (is_file($file)) //directory check
        {
            $data = implode("",file($file));
                    $this->addFile($data,$file);
                }
        }
        //out file
        $fp=fopen($filedes,"w");
        if(file_exists($filedes))
        {
            fwrite($fp,$this->file());
            fclose($fp);
        }
        else
            echo $nls_file_noexit;
    }
    //End Zip Function
    //Unzip Function


    /**
    * Redirect URL
    */


    function redirect($url){
        if(headers_sent()){
            echo "<script>document.location.href='$url';</script>";
        }else{
             header( 'HTTP/1.1 301 Moved Permanently' );
             header("Location: " . $url);
        }
    }    
    
    /**
    * @desc Get message from code of authentication code
    */
    function getMessage($code){
        global $nls_login_error, $nls_need_login_error, $nls_login_fail, $nls_login_blocked, 
            $nls_login_not_activiated, $nls_login_not_right_perm, $nls_login_empty;
         switch($code){
             case SESSION_TIMEOUT:
                return $nls_login_session_timeout;
             case NOT_LOGON:
                return $nls_need_login_error;
             case WRONG_USER_PWD:
                return $nls_login_fail;
             case BLOCKED_ERROR:
                return $nls_login_blocked;
             case NOT_ACTIVIATED:
                return $nls_login_not_activiated;
             case NOT_RIGHT_PERM:
                return $nls_login_not_right_perm;
             case EMPTY_USER_PWD:
                return $nls_login_empty;
         }

    }
    
   
    /**
    * @desc Order Code with 8 digit
    */
    function generateCode(){
        $res = "";
        for($i = 0; $i < 8; $i++){
            mt_srand((double)microtime()*1000000);    
            $res .= mt_rand(0,9);
        }
        return $res;
    }
    
    function getNumDayOfMonth($month, $year){
        switch($month){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            case 2:
                if (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0){
                    return 29;
                }
                return 28;            
        }
    } 
    
    function getStartDayOfMonth($month, $year){
        $date = date("Y-m-d", mktime(0, 0, 0, $month, 1, $year));
        return $date["wday"];
    }
    
	function getParameter($name, $default = null) {
        $result = isset($_GET[$name]) ? $_GET[$name] : null;
        if (!isset($result)) {
            $result = isset($_POST[$name]) ? $_POST[$name] : null;
        }
        if (!isset($result)) return $default;
        return $result;
    }
	function formatInputStr($str)
	{
		$str=stripslashes($str);
		$str=addslashes($str);
		return $str;
	}
	
	function getDate(){
        date_default_timezone_set('Asia/Saigon');
		$date = date('Y-m-d h:i:s ', time());
        return $date; 
    }
    
	function getDateTime(){
        date_default_timezone_set('Asia/Saigon');
		$date = date('Ymdhis ', time());
        return $date; 
    }
    
    function uploadAndResizeImage($imgUpload, $thumbsize, $bigsize){
		$wh = $imgUpload->imgSize($thumbsize, $bigsize);
		$imgfile = $imgUpload->re;
		@unlink($IMG_TEMP_PATH.$image);
		return array($imgfile, $wh[0], $wh[1]); 
    }
    
	function getVideoId($url){
		$url = $url.'&';
		$pattern = '/v=(.+?)&+/';
		preg_match($pattern, $url, $matches);
		return ($matches[0]);
	}
}
?>